import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_reader/model/novel.dart';
import 'package:flutter_reader/res/colors.dart';
import 'package:flutter_reader/ui/novel_detail/novel_detail_cell.dart';
import 'package:flutter_reader/ui/novel_detail/novel_detail_header.dart';
import 'package:flutter_reader/ui/novel_detail/novel_detail_recommend_view.dart';
import 'package:flutter_reader/ui/novel_detail/novel_detail_toolbar.dart';
import 'package:flutter_reader/utils/request.dart';
import 'package:flutter_reader/utils/screen.dart';
import 'package:flutter_reader/utils/toast.dart';

class NovelDetailPage extends StatefulWidget {
  final Novel novel;
  NovelDetailPage(this.novel);

  @override
  _NovelDetailPageState createState() => _NovelDetailPageState();
}

class _NovelDetailPageState extends State<NovelDetailPage> with RouteAware {
  Novel novel;
  List<Novel> recommendNovels = [];
  ScrollController scrollController = ScrollController();
  double navAlpha = 0;

  @override
  void initState() {
    super.initState();
    fetchData();

    scrollController.addListener(() {
      var offset = scrollController.offset;
      if (offset < 0) {
        if (navAlpha != 0) {
          setState(() {
            navAlpha = 0;
          });
        }
      } else if (offset < 50) {
        setState(() {
          navAlpha = 1 - (50 - offset) / 50;
        });
      } else if (navAlpha != 1) {
        setState(() {
          navAlpha = 1;
        });
      }
    });
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var novel = this.novel == null ? this.widget.novel : this.novel;
    return Scaffold(
      body: AnnotatedRegion(
        value: navAlpha > 0.5
            ? SystemUiOverlayStyle.dark
            : SystemUiOverlayStyle.light,
        child: Stack(
          children: [
            Column(
              children: [
                Expanded(
                  child: ListView(
                    controller: scrollController,
                    padding: EdgeInsets.only(top: 0),
                    children: [
                      NovelDetailHeader(novel),
                      _buildSummaryView(novel),
                      SizedBox(height: 10),
                      NovelDetailCell(
                        iconName: 'img/detail_latest.png',
                        title: '最新',
                        subtitle: novel.lastChapter.title,
                        attachedWidget: Text(
                          novel.status,
                          style: TextStyle(
                              fontSize: 14,
                              color: novel.isSerial
                                  ? MyColors.blue
                                  : MyColors.primary),
                        ),
                      ),
                      NovelDetailCell(
                        iconName: 'img/detail_chapter.png',
                        title: '目录',
                        subtitle: '共${novel.chapterCount}章',
                      ),
                      SizedBox(height: 10),
                      NovelDetailRecommendView(recommendNovels),
                    ],
                  ),
                ),
                NovelDetailToolbar(novel),
              ],
            ),
            _buildNavigationBar(novel),
          ],
        ),
      ),
    );
  }

  // 书籍描述
  Widget _buildSummaryView(Novel novel) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(15),
      child: Text(novel.introduction.trim(), style: TextStyle(fontSize: 14)),
    );
  }

  Widget _buildNavigationBar(Novel novel) {
    return Stack(
      children: <Widget>[
        Opacity(
          opacity: navAlpha,
          child: Container(
            decoration: BoxDecoration(color: MyColors.white, boxShadow: [
              BoxShadow(color: Color(0x22000000), blurRadius: 8)
            ]),
            padding: EdgeInsets.fromLTRB(5, Screen.topSafeHeight, 0, 0),
            height: Screen.navigationBarHeight,
            child: Row(
              children: <Widget>[
                Container(
                  width: 44,
                  child: GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: Image.asset('img/pub_back_gray.png')),
                ),
                Expanded(
                  child: Text(
                    novel.name,
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    textAlign: TextAlign.center,
                  ),
                ),
                Container(width: 44),
              ],
            ),
          ),
        )
      ],
    );
  }

  // 加载书籍详情数据
  Future<void> fetchData() async {
    try {
      var novel = await Request.getNovelDetail(this.widget.novel.id);
      var recommendNovels =
          await Request.getNovelRecommend(this.widget.novel.id);
      setState(() {
        this.novel = novel;
        this.recommendNovels = recommendNovels;
      });
    } catch (e) {
      Toast.show(e.toString());
    }
  }
}
